package com.heima.gateway.filter;

import com.heima.utils.common.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
@Component
@Order(-1)
public class AuthorizeFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取request和response对象
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();

        //2.判断是否是登录
        if(StringUtils.contains(request.getURI().getPath(),"/login/in")){
            //放行
            return chain.filter(exchange);
        }

        //3.获取token
        HttpHeaders headers = request.getHeaders();
        String token = headers.getFirst("token");
        //4.判断token是否存在
        if(StringUtils.isEmpty(token)){
            //当前token为空
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //5.判断token是否有效

        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
        if(claimsBody==null){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        int result = AppJwtUtil.verifyToken(claimsBody);
        //检验token是否过期
        if(result!=0&&result!=-1){
            //过期
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //获取token中的用户信息
        Long userId = claimsBody.get("id", Long.class);
        //将用户信息路由到下游服务 ,mutate：对请求对象进行重构
        ServerHttpRequest httpRequest = request.mutate().headers(httpHeaders -> httpHeaders.add("userId", userId + "")).build();
        //对交换机进行重构，将新的请求对象设置到交换机中
        ServerWebExchange webExchange = exchange.mutate().request(httpRequest).build();
        //放行
        return chain.filter(webExchange);
    }
}
